package org.kl.auditsupervision.web.fnd;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.joda.time.DateTime;
import org.kl.bf.entity.basic.Post;
import org.kl.bf.entity.easyui.EasyuiUtils;
import org.kl.bf.utils.ExcelWriter;
import org.kl.bf.utils.KLServlets;
import org.kl.bf.web.base.BasicController;
import org.kl.auditsupervision.entity.fnd.FndPost;
import org.kl.auditsupervision.entity.fnd.Org;
import org.kl.auditsupervision.service.fnd.FndPostService;
import org.kl.auditsupervision.service.fnd.OrgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.MediaTypes;

/**
 * @author Code Generator
 * @since 2015-09-09 10:59:57
 * @see 岗位表 岗位表
 */
@Controller
@RequestMapping(value = "/fnd/fndPost")
public class FndPostController extends BasicController {

	@Autowired
	private FndPostService fndPostService;
	@Autowired
	private OrgService orgService;

	@RequiresPermissions(value = "fndPost:list")
	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "fnd/fndPostList";
	}

	@RequestMapping(value = "dataGrid", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String dataGrid(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		Page<FndPost> posts = fndPostService.getPostInfo(searchParams, pageNumber, pageSize, sortType, orderType);
		return EasyuiUtils.buildEasyuiGridJsonString(posts.getContent(), (int) posts.getTotalElements());
	}

	@RequestMapping(value = "postList", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String postList(@RequestParam(value = "orgId", defaultValue = "-1") String orgId) {
		List<FndPost> postList = new ArrayList<FndPost>();
		FndPost p = new FndPost();
		p.setPostName("所有内容");
		p.setId(" ");
		postList.add(p);
		if (!orgId.equals("-1")) {
			postList.addAll(fndPostService.findByOrgIdAndEnable(orgId));
		}
		String result = jsonMapper.toJson(postList);
		return result;
	}


	@RequestMapping(value = "showInfo/{id}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String showInfo(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request,
			@PathVariable("id") String id) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		searchParams.put("EQ_org.id", id);
		searchParams.put("EQ_enable", "1");
		Page<FndPost> posts = fndPostService.getPostInfo(searchParams, pageNumber, pageSize, sortType, orderType);
		return EasyuiUtils.buildEasyuiGridJsonString(posts.getContent(), (int) posts.getTotalElements());
	}

	@RequiresPermissions("fndPost:export")
	@RequestMapping(value = "excelExport", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String excelExport(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request,
			HttpServletResponse response, @RequestParam(value = "orgId", defaultValue = "-1") String orgId) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		if (!orgId.equals("-1")) {
			searchParams.put("EQ_org.id", orgId);
		}
		Page<FndPost> posts = fndPostService.getPostInfo(searchParams, pageNumber, 0, sortType, orderType);
		try {
			// 输出Excel文件.
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-Disposition",
					"attachment;filename=\""
							+ new String(("岗位信息" + new DateTime().toString("yyyyMMddHHmmss") + ".xls").getBytes("gb2312"), "ISO8859-1")
							+ "\"");
			ExcelWriter.exportExcel("岗位信息", Post.class, posts.getContent(), response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				response.getOutputStream().flush();
				response.getOutputStream().close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@RequiresPermissions("fndPost:update")
	@RequestMapping(value = "update", method = RequestMethod.POST, produces = { MediaTypes.TEXT_HTML_UTF_8,
			MediaTypes.JSON_UTF_8 })
	@ResponseBody
	public String update(@Valid @ModelAttribute("post") FndPost fndPost, @RequestParam(value = "orgId", defaultValue = "-1") String orgId,
			RedirectAttributes redirectAttributes, HttpSession session, ServletRequest request) {
		//List<FndPost> postList = new ArrayList<FndPost>();
		if (StringUtils.equals(fndPost.getDescription(), "请在这里输入职位描述")) {
			fndPost.setDescription(null);
		}


			if ((StringUtils.isBlank(fndPost.getPostNo())) || (StringUtils.isBlank(fndPost.getPostName()))) {
				return ajaxMsg("编辑失败!岗位编号以及岗位名称必须输入", false, null);
			}
			//if ((fndPostService.findByPostNoAndOrgId(fndPost.getPostNo(), fndPost.getOrg().getId()) == null)
			//		&& (fndPostService.findByPostNameAndOrgId(fndPost.getPostName(), fndPost.getOrg().getId()) == null)) {
				try {
					fndPostService.savePost(fndPost);
				} catch (Exception e) {
					e.printStackTrace();
					return ajaxMsg("编辑失败[" + e.getMessage() + "]", false, null);
				}
				return ajaxMsg("编辑成功", true, null);
		//	} else {
		//		return ajaxMsg("编辑失败!岗位编号或岗位名称已存在", false, null);
		//	}

		
	}

	// 获取显示组织名称
	@RequiresPermissions("fndPost:update")
	@RequestMapping(value = "orgList/{id}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String orgList(@PathVariable("id") String id, RedirectAttributes redirectAttributes, HttpSession session) {
		List<Org> orgs = orgService.getAllOrg();
		String result = jsonMapper.toJson(orgs);
		return result;
	}

	@RequiresPermissions({ "fndPost:delete", "post:update" })
	@RequestMapping(value = "delete/{id}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String delete(@PathVariable("id") String id, RedirectAttributes redirectAttributes, HttpSession session) {
		fndPostService.deletePost(id);
		return ajaxMsg("删除成功", true, null);
	}

	@RequiresPermissions({ "fndPost:delete" })
	@RequestMapping(value = "multiDelete", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String multiDelete(@RequestParam(value = "ids", defaultValue = "") String ids) {
		String msg = "";
		try {
			msg = fndPostService.multiDelete(ids);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("删除失败:" + e.getMessage(), false, null);
		}
		return ajaxMsg("删除成功:" + msg, true, null);
	}

	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void init(
			@RequestParam(value = "id", defaultValue = "-1") String id,
			Model model) {
		if (!id.equals("-1")) {
			model.addAttribute("Post", fndPostService.getOne(id));
		}
	}

}
